package camid.services.nodemanager;

import java.io.Serializable;

import camid.distribution.broker.Requestor;
import camid.distribution.interceptor.InvocationInterceptor;
import camid.distribution.protocol.Endpoint;
import camid.distribution.protocol.InvocationDescriptor;
import camid.distribution.protocol.MethodRequestMessage;
import camid.distribution.protocol.MethodResponseMessage;
import camid.distribution.protocol.ResponseStatus;
import camid.services.nameservice.INameService;

public class ForwarderRequestorInterceptor implements InvocationInterceptor {

	private INameService ns;
	
	private Requestor requestor;
	
	public ForwarderRequestorInterceptor(INameService ns, Requestor requestor) {
		this.ns = ns;
		this.requestor = requestor;
	}

	@Override
	public void beforeInvocation(MethodRequestMessage requestMessage)
			throws Exception {
		// TODO Auto-generated method stub

	}

	@Override
	public void afterInvocation(MethodResponseMessage responseMessage)
			throws Exception {
		
		
		Object response = null;
		
		if(responseMessage != null) 
		{
			response = responseMessage.getResponse();
		}
		
		if(response != null && response instanceof ForwardingException)
		{
			ForwardingException e = (ForwardingException) response;
			InvocationDescriptor descriptor = e.getDescriptor();
				
	 		Endpoint ep = ns.lookup(descriptor.getObjectId());
	 			
	 		MethodRequestMessage newRequestMessage = new MethodRequestMessage();
	 		newRequestMessage.setDescriptor(descriptor);
	 		response = requestor.request(ep, descriptor);
	 		responseMessage.setResponse((Serializable)response);
	 		responseMessage.setEndpoint(ep);
	 		if(response instanceof Exception)
	 		{
	 			responseMessage.setStatus(ResponseStatus.SERVICE_EXCEPTION);
	 		}
	 		else
	 		{
	 			responseMessage.setStatus(ResponseStatus.SUCCESS);
	 		}
	 		
		}

	}

}
